/*
  为组件提供导出excel逻辑

  data:
    exportFileName(导出的文件名) string 默认''
    表头列统一为tile(name),导入才可以解析
    导出的数据要有独一的id,且不能修改

  methods
    exportData(输入一个数组[{}]，里面为对象. 数组头一个是表头，后面是表的数据，表格字段部分要做转换) param{array}

  使用实例
    import ExportMixin from "@/mixins/table/export.mixin";
    mixins: [ExportMixin],
    <el-button type="primary" @click="exportData([{gaga:123}])">导出excel</el-button>
*/

var XLSX = require("xlsx")
import FileSaver from 'file-saver'

const ExportMixin = {
  props: {},
  data() {
    return { exportFileName: 'voerkaweb' }
  },
  watch: {},
  created() { },
  methods: {
    // 传入导出data，data要为数组
    exportData(data) {
      if (!Array.isArray(data)) {
        this.$notify({
          message: '类型错误',
          type: 'warning'
        })
      } else if (!data.length) {
        this.$notify({
          message: '数据不能为空',
          type: 'warning'
        })
      }
      // 转换数据
      const book = XLSX.utils.book_new()
      const sheet = XLSX.utils.json_to_sheet(data, { skipHeader: false })
      XLSX.utils.book_append_sheet(book, sheet)
      const wbout = XLSX.write(book, {
        bookType: 'xlsx',
        bookSST: false,
        type: 'binary'
      })
      const blob = new Blob([this.toBuffer(wbout)], {
        type: 'application/octet-stream'
      })
      // 保存导出
      FileSaver.saveAs(blob, `${this.exportFileName}.xlsx`)
    },
    toBuffer(wbout) {
      const buf = new ArrayBuffer(wbout.length)
      const view = new Uint8Array(buf)
      for (let index = 0; index !== wbout.length; ++index) {
        view[index] = wbout.charCodeAt(index) & 0xff
      }
      return buf
    }
  }
}

export default ExportMixin
